<?php

namespace App\Http\Admin\Controllers;

use App\Http\Admin\Response;
use App\Jobs\errorlogmq;
use App\Jobs\Queue;
use App\Models\RequestErr;
use App\Models\Resources;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class ExtendController extends Controller
{

    //图片上传
	public function uploadImage(Request $request)
	{
		if ($request->hasFile('file') && $request->file('file')->isValid()) {
			$type = ['png','jpg','jpeg'];
			$file= $request->file('file');
			if(!in_array($file->getClientOriginalExtension(),$type)){
				return Response::error('文件格式错误');
			}

			$file_name = uniqid().'.'.$file->getClientOriginalExtension();
			$las_path = '/Upload/image/'.date('Y-m-d');
			$file_path = public_path($las_path);
			if (!is_dir($file_path)) {
                mkdir($file_path, 777);
			}

			$path = $file->move($file_path,$file_name);


			$sql = Resources::create([
				'res_type' => $file->getClientOriginalExtension(),
				'res_url' => $las_path.'/'.$file_name,
				'res_name' => $file_name,
				'res_name_u' => $file->getClientOriginalName(),
				'res_size' => $file->getClientSize()
			]);

			$id = $sql->id;

            return Response::success(['id'=>$id,'url'=>$las_path.'/'.$file_name]);
        }
        return Response::error('未检测到上传文件');
    }

    //错误记录
    public function SaveErrorLogger()
    {
		//取出访问的错误
		$i = 0;
		//监听执行的错误把错误放到数据库
		$this->dispatch(new errorlogmq($i++));

		return ltrim(parse_url("https://www.baidu.com/test/1w",PHP_URL_PATH),'/');;
	}

	/**
     * 创建秒杀列表
     */
    public function createList()
    {
        $count = 30;
		$redisKey = 'goods_list';

        for ($i = 1; $i <= $count; $i++) {

            // 测试用，防止数据错误
            if (Redis::llen($redisKey) >= $count) {
                break;
            }
            Redis::rpush($redisKey, $i);
		}

		return "添加成功";
	}

	/**
	 * 开始秒杀
	 */
	public function buy()
    {
		// 随机用户名，无意义，仅做标记
        $username = Hash::make(now());

        if ($goodsId = Redis::lpop('goods_list')) {
			// 购买成功  进入消费队列
			$this->dispatch(new Queue($username));
            Redis::hset('buy_success', $goodsId, $username);//记录成功
        } else {
            // 购买失败  推出
            Redis::incr('buy_fail');//记录失败
        }
    }

	//快速搜索分页
	public function pagination($lists, $request)
	{

		//利用scope查询
		if (array_key_exists('query', $request)) {
			if (!empty($request['query'] && is_array($request['query']))) {
				foreach ($request['query'] as $key => $val) {
					if (!empty($val)) {
						//return $key;
						$lists = $lists->{$key}($val);
					}
				}
			}
		}


		$count = $lists->count('id');
		//分页拼装
		$limit = $request['limit'];
		$page = ($request['page']-1)*$limit;


		$lists = $lists->skip($page)->take($limit)->get()->toArray();

		$records = array();
		$records['count'] = $count;
		$records['list'] = $lists;

		return $records;
	}

	//快速表单验证
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];
        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }
        $messages = [
            'required' => ':attribute不能为空',
		];
        $validator = Validator::make($check, $rules,$messages, $attributes);
        $message = $validator->getMessageBag();
        return $message->first();
    }

}
